package xyz.labmem.lipx.core.util

import cn.hutool.core.io.file.FileReader
import cn.hutool.core.io.file.FileWriter
import com.alibaba.fastjson2.JSON
import com.alibaba.fastjson2.JSONObject
import xyz.labmem.lipx.core.context.AppContext
import xyz.labmem.lipx.core.entity.ServerConfig
import java.io.File


/**
 * @description: 持久化配置信息
 * @author: ltty
 * @date: 2022/6/15 12:23
 */

class ServerConfigDataUtil {

    companion object {

        val sap = "${xyz.labmem.lipx.core.tool.appPath}/lipxServer"

        fun init() {
            val dir = File(sap)
            if (!dir.exists()) {
                dir.mkdirs()
            }
            refreshData()
        }


        private fun read(): JSONObject? {
            File("$sap/lipxData.json").apply {
                if (exists()) {
                    val data = FileReader(this).readString()
                    try {
                        return JSON.parseObject(data)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                } else {
                    write(ServerConfig())
                    return read()
                }
            }
            return null
        }

        //写入文件
        fun write(config: ServerConfig) {
            FileWriter("$sap/lipxData.json").write(JSON.toJSONString(config))
        }

        fun refreshData() {
            AppContext.Server.cacheData = read()?.toJavaObject(ServerConfig::class.java)
        }

    }

}